package com.doupi.partner.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * 验证工具
 * 
 * @author Super Jens Wang
 *
 * @version 1.0 @ 2016年7月20日 下午11:08:05
 */
public class ValidateUtils {

	private static final Logger logger = LoggerFactory.getLogger(ValidateUtils.class);

	private static Validator validator;

	static {
		try {
			ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
			validator = factory.getValidator();
		} catch (Exception e) {
			logger.error("初始化验证器失败了， msg={}", e);
		}
	}

	/**
	 * 验证对象
	 * 
	 * @param obj
	 *            - 不为null 说明验证有错误，前提是注解验证错误信息一定要写
	 */
	public static List<String> validate(Object obj) {
		Set<ConstraintViolation<Object>> constraintViolations = validator.validate(obj);
		if (constraintViolations == null || constraintViolations.isEmpty()) {
			return Collections.emptyList();
		}

		List<String> messages = new ArrayList<>();
		for (ConstraintViolation<Object> cons : constraintViolations) {
			messages.add(cons.getMessage());
		}

		return messages;
	}

	/**
	 * 验证并抛出运行异常
	 */
	public static void validateAndThrowRuntimeException(Object obj) throws RuntimeException {
		List<String> messages = validate(obj);
		if (!messages.isEmpty()) {
			throw new RuntimeException(StringUtils.join(messages, ","));
		}
	}
}
